

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

using JTC.MiniCommerce.Core;
using JTC.MiniCommerce.Store;
using SubSonic.Utilities;
using Img = System.Drawing;
using System.Collections.Generic;
using System.IO;
using JTC.MiniCommerce.Localization;

namespace JTC.MiniCommerce.Web {
  public partial class product : System.Web.UI.Page {

    #region Member Variables

    private int productId = 0;
    private Product _product;
    private List<System.Web.UI.WebControls.Image> imageList = new List<System.Web.UI.WebControls.Image>();

    #endregion

    #region Page Events

    /// <summary>
    /// Handles the Load event of the Page control.
    /// </summary>
    /// <param name="sender">The source of the event.</param>
    /// <param name="e">The <see cref="T:System.EventArgs"/> instance containing the event data.</param>
    protected void Page_Load (object sender, EventArgs e) {
      try {
        productId = Utility.GetIntParameter("pid");
        SetProductProperties();
        LogProductBrowse();
        LoadProduct();
        LoadPageTitle();
        LoadProductImages();
        LoadDescriptors();
        LoadReviews();
        LoadCrossSells();
        if(User.Identity.IsAuthenticated) {
          //only allow them to review if they haven't reviewed before (select even the non-approved reviews)
          if(_product.ReviewRecords().Find(delegate(Review review) { return review.CreatedBy == WebUtility.GetUserName();}) == null) {
            pnlReview.Visible = true;
          }
        }
      }
      catch (Exception ex) {
        Logger.Error(typeof(product).Name + ".Page_Load", ex);
      }
    }

    /// <summary>
    /// Handles the Click event of the btnAddToCart control.
    /// </summary>
    /// <param name="sender">The source of the event.</param>
    /// <param name="e">The <see cref="T:System.EventArgs"/> instance containing the event data.</param>
    protected void btnAddToCart_Click (object sender, EventArgs e) {
      try {
        if (Master.SiteSettings.LoginRequirement == LoginRequirement.Add_To_Cart) {
          if (!User.Identity.IsAuthenticated) {
            Response.Redirect(string.Format("login.aspx?ReturnUrl={0}", Request.Url), true);
          }
        }
        int quantity = 1;
        string sku = string.Empty;
        if (ddlQuantity.Visible) {
          int.TryParse(ddlQuantity.SelectedValue, out quantity);
        }
        else {
          int.TryParse(txtQuantity.Text.Trim(), out quantity);
        }
        sku = productAttributes.GetSku();
        decimal pricePaid = _product.OurPrice;
        Store.AttributeCollection selectedAttributes = productAttributes.SelectedAttributes;
        foreach (Store.Attribute attribute in selectedAttributes) {
          foreach (AttributeItem attributeItem in attribute.AttributeItemCollection) {
            pricePaid += attributeItem.Adjustment;
          }
        }
        string selectAttributesString = selectedAttributes.ToString();
        OrderController orderController = new OrderController();
        orderController.AddItemToOrder(WebUtility.GetUserName(), _product.ProductId, _product.Name, sku, quantity, pricePaid, _product.Weight, selectAttributesString);
        Response.Redirect("~/cart.aspx", true);
      }
      catch (Exception ex) {
        Logger.Error(typeof(product).Name + ".btnAddToCart_Click", ex);
        throw;
      }
    }

    #endregion

    #region Methods

    #region Private

    /// <summary>
    /// Loads the cross sells.
    /// </summary>
    private void LoadCrossSells () {
      ProductCollection productCollection = new ProductController().FetchProductCrossSells(productId);
      crossSells.ProductCollection = productCollection;
      if (productCollection.Count == 0) {
        lblCrossSells.Visible = false;
      }
    }

    /// <summary>
    /// Loads the descriptors.
    /// </summary>
    private void LoadDescriptors () {
      DescriptorCollection descriptorCollection = _product.DescriptorRecords();
      descriptorCollection.Sort(Descriptor.Columns.SortOrder, true);
      AjaxControlToolkit.TabPanel tabPanel;
      foreach (Descriptor descriptor in descriptorCollection) {
        tabPanel = new AjaxControlToolkit.TabPanel();
        tabPanel.HeaderText = descriptor.Title;
        tabPanel.Controls.Add(new LiteralControl(HttpUtility.HtmlDecode(descriptor.DescriptorX)));
        tcDescriptors.Tabs.Add(tabPanel);
      }
      tcDescriptors.ActiveTabIndex = 0;
    }

    /// <summary>
    /// Loads the reviews.
    /// </summary>
    private void LoadReviews() {
      ReviewCollection reviewCollection = new ReviewController().FetchByProductIdAndIsApproved(productId);
      if(reviewCollection.Count > 0) {
        reviewCollection.Sort(Review.Columns.CreatedOn, false);
        rptrReviews.DataSource = reviewCollection;
        rptrReviews.DataBind();
      }
      else {
        lblNoReviews.Visible = true;
      }
    }

    /// <summary>
    /// Loads the page title.
    /// </summary>
    private void LoadPageTitle () {
      string pageTitle = string.Format("{0} :: {1}", Master.SiteSettings.SiteName, _product.Name);
      Page.Title = pageTitle;
    }

    /// <summary>
    /// Loads the product.
    /// </summary>
    private void LoadProduct () {
      _product = new Product(productId);
      productAttributes.Product = _product;
      lblProductName.Text = _product.Name;
      lblOurPriceAmount.Text = StoreUtility.GetFormattedAmount(_product.OurPrice, true);
      ajaxRating.CurrentRating = _product.Rating;
      lblShortDescription.Text = HttpUtility.HtmlDecode(_product.ShortDescription);
      if (Master.SiteSettings.DisplayRetailPrice) {
        lblRetailPriceAmount.Text = StoreUtility.GetFormattedAmount(_product.RetailPrice, true);
        pnlRetailPrice.Visible = true;
        pnlYouSave.Visible = true;
        lblYouSaveAmount.Text = string.Format("{0}&nbsp;({1})", StoreUtility.GetFormattedAmount(_product.YouSaveAmount, true), _product.YouSavePercentage.ToString("p"));
      }
      if (_product.SkuRecords().Count > 0) {
        if(_product.SkuRecords().Count == 1) {//there is only 1 Sku, so load the inventory
          productAttributes.GetInventory(_product.SkuRecords()[0].SkuX.ToString());
        }
        else {
          ddlQuantity.Enabled = false;
          btnAddToCart.Enabled = false;
        }
      }
      if(_product.AllowNegativeInventories) {
        ddlQuantity.Visible = false;
        txtQuantity.Visible = true;
        rfvQuantity.Visible = true;
      }
    }

    /// <summary>
    /// Sets the product properties.
    /// </summary>
    private void SetProductProperties () {
      LocalizationUtility.AddLabelText(lblRetialPrice);
      LocalizationUtility.AddLabelText(lblYouSave);
      LocalizationUtility.AddLabelText(lblOurPrice);
      ajaxRating.GroupingText = LocalizationUtility.GetText("lblAverageRating");
      LocalizationUtility.AddLabelText(lblReviewsTitle);
      LocalizationUtility.AddLabelText(lblNoReviews);
      LocalizationUtility.AddLabelText(lblCrossSells);
      LocalizationUtility.AddPanelText(pnlAddToCart);
    }

    /// <summary>
    /// Logs the product browse.
    /// </summary>
    private void LogProductBrowse () {
      if (Master.SiteSettings.CollectBrowsingProduct) {
        BrowsingLog browsingLog = new BrowsingLog();
        browsingLog.BrowsingBehaviorId = (int)BrowsingBehaviour.Browsing_Product;
        browsingLog.RelevantId = productId;
        browsingLog.UserName = WebUtility.GetUserName();
        browsingLog.Url = Request.Url.ToString();
        browsingLog.SessionId = WebUtility.SessionId();
        browsingLog.Save("System");
      }
    }

    /// <summary>
    /// Loads the product images.
    /// </summary>
    private void LoadProductImages () {
      ImageCollection imageCollection = _product.ImageRecords();
      imageCollection.Sort("SortOrder", true);
      Img.Image drawnImage;
      System.Web.UI.WebControls.Image displayImage;
      foreach (Store.Image image in imageCollection) {
        if (File.Exists(Server.MapPath(image.ImageFile))) {
          drawnImage = Img.Image.FromFile(Server.MapPath(image.ImageFile));
          displayImage = new System.Web.UI.WebControls.Image();
          displayImage.ImageUrl = image.ImageFile;
          displayImage.Attributes.Add("onmouseover", string.Format("{0}.src='{1}';document.getElementById('{2}').innerHTML='{3}';", defaultImage.ClientID, Page.ResolveUrl(displayImage.ImageUrl), imageCaption.ClientID, image.Caption));
          if (drawnImage.Width > drawnImage.Height) {
            if (drawnImage.Width > 32) {
              displayImage.Width = 32;
              displayImage.Height = drawnImage.Height * 32 / drawnImage.Width;
            }
          }
          else { //portrait
            if (drawnImage.Height > 32) {
              displayImage.Height = 32;
              displayImage.Width = drawnImage.Width * 32 / drawnImage.Height;
            }
          }
          imageList.Add(displayImage);
        }
      }
      imageList.TrimExcess();
      dlImages.DataSource = imageList;
      dlImages.DataBind();
      if (File.Exists(Server.MapPath(imageCollection[0].ImageFile))) {
        defaultImage.ImageUrl = imageCollection[0].ImageFile;
      }
      imageCaption.Text = imageCollection[0].Caption;
    }

    #endregion

    #endregion

    #region Properties

    /// <summary>
    /// Gets the update panel.
    /// </summary>
    /// <value>The update panel.</value>
    public UpdatePanel UpdatePanel {
      get {
        return upCart;
      }
    }

    /// <summary>
    /// Gets the quantity.
    /// </summary>
    /// <value>The quantity.</value>
    public DropDownList Quantity {
      get {
        return ddlQuantity;
      }
    }

    /// <summary>
    /// Gets or sets the product.
    /// </summary>
    /// <value>The product.</value>
    public Product Product {
      get {
        return _product;
      }
      set {
        _product = value;
      }
    }

    /// <summary>
    /// Gets the add to cart.
    /// </summary>
    /// <value>The add to cart.</value>
    public Button AddToCart {
      get {
        return btnAddToCart;
      }
    }

    #endregion
    
  }
}
